package user

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"net/http"
	"strconv"
	"weekly-exam/config"
	"weekly-exam/internal/model/dao"
	"weekly-exam/internal/model/service"
)

type Node struct {
	WsConn *websocket.Conn
	Data   chan []byte
}

var clientMap = make(map[int]*Node)

type MessageRequest struct {
	Content  string `json:"content"`
	UserId   int    `json:"userId"`
	FriendId int    `json:"friendId"`
	Type     int    `json:"type"`
}

func ChatUser(c *gin.Context) {
	value, _ := strconv.Atoi(c.Query("friendId"))
	upgrader := websocket.Upgrader{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}
	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		return
	}
	node := &Node{
		WsConn: conn,
		Data:   make(chan []byte, 1024),
	}
	clientMap[value] = node
	var json MessageRequest
	userId := json.UserId
	friendId := json.FriendId
	var friends dao.Friend
	config.DB.Where("user_id=?", userId).First(&friends)
	if friends.FriendId != friendId {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    500,
			"message": "两人不是好友请添加好友",
		})
		return
	}
	go SendMessage(node)
	go ReadMessage(node)
}

func ReadMessage(node *Node) {
	for {
		_, data, err := node.WsConn.ReadMessage()
		if err != nil {
			return
		}
		messageRequest := MessageRequest{}
		json.Unmarshal(data, &messageRequest)
		recvDate, ok := clientMap[messageRequest.UserId]
		if !ok {
			continue
		}
		recvDate.Data <- data
		service.CreateMessage(messageRequest.UserId, messageRequest.FriendId, messageRequest.Content)
	}
}

func SendMessage(node *Node) {
	for {
		select {
		case data := <-node.Data:
			err := node.WsConn.WriteMessage(1, data)
			if err != nil {
				return
			}
		}
	}
}
